package com.dnjn.happiness.oss.service;

import com.dnjn.happiness.common.core.utils.uuid.IdUtils;
import com.dnjn.happiness.oss.config.HappinessOssProperties;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


@Service
public class UploadServiceImpl implements UploadService {

    // TODO 明天写这块路径
    @Autowired
    HappinessOssProperties imageProperties;


    @Override
    public String uploadImage(MultipartFile file) {
        //1.验证文件是不是空  ObjectUtils.isEmpty(file) 文件名是空    file.isEmpty()文件大小
        if (ObjectUtils.isEmpty(file) || file.isEmpty()) {
            throw new RuntimeException("文件不能为空");
        }


        //2,验证文件类型
//        String contentType=file.getContentType();
//        List<String> types = imageProperties.getTypes();
//        if(!types.contains(contentType)){
//            String message=types.stream()
//                    .map(type->type.substring(type.indexOf("/")+1))
//                    .collect(Collectors.joining(","));
//            throw new RuntimeException("仅支持"+message +"类型");
//        }


        //3,新文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));//包括这个".
//        String uuid= IdUtil.simpleUUID();//生成随机码 hutool
        String uuid = IdUtils.simpleUUID();
        String filename = StringUtils.join(uuid, extension);


        //4创建上传目录
        File uploadDir = new File(imageProperties.getProfile());
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        //5.创建目标文件
        File destFile = new File(uploadDir, filename);


        //6.执行文件上传
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            throw new RuntimeException("上传失败!");
        }


        //7.返回结果
        String prefix = imageProperties.getProfile();
        return prefix.endsWith("/") ? StringUtils.join(prefix, filename)
                : StringUtils.join(prefix, "/", filename);


    }
}